package archimede;

import it.sauronsoftware.ftp4j.FTPClient;
import it.sauronsoftware.ftp4j.FTPFile;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GraphicsEnvironment;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.awt.geom.Point2D;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.MalformedURLException;
import java.util.HashMap;
import java.util.Properties;
import java.util.Scanner;

import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JScrollBar;
import javax.swing.JScrollPane;
import javax.swing.JSeparator;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

import net.miginfocom.swing.MigLayout;

import org.apache.commons.io.FileUtils;

import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.ExceptionConverter;
import com.itextpdf.text.FontFactory;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.pdf.ColumnText;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfPageEventHelper;
import com.itextpdf.text.pdf.PdfTemplate;
import com.itextpdf.text.pdf.PdfWriter;

/**
 * Main class
 * 
 * @author Alex
 */
public class StartingWindow {
  /**
   * frame contenente tutti i pannelli
   */
  private JFrame window = new JFrame("EUREKA - ARCHIMEDE");
  /**
   * panel containing tab pages
   */
  private JPanel projectPanel = new JPanel();
  /**
   * height of window
   */
  private int height;
  /**
   * width of window
   */
  private int width;
  /**
   * count RTD
   */
  private int countRtd = 0;
  /**
   * count RTD
   */
  private int lastCountRtd = 0;
  /**
   * nome progetto caricato
   */
  private String nameProject;
  /**
   * ultimo percorso aperto per la ricerca di immagini
   */
  private String lastPath = "";
  /**
   * tab of pages
   */
  private JTabbedPane tab = new JTabbedPane();
  /**
   * progetto amministratore
   */
  public final int AMMINISTRATORE = 0;
  /**
   * progetto silver
   */
  public final int SILVER = 1;

  /**
   * 
   */
  private HashMap<String, String> tagList;

  /**
   * menubar contenente i pulsanti SCARICA PROGETTO || APRI PROGETTO || NUOVO ||
   * ELIMINA || INVIA || SALVA
   */
  private JMenuBar menubar = new JMenuBar() {
    /** Stroke size. it is recommended to set it to 1 for better view */
    protected int strokeSize = 1;
    /** Double values for Horizzontal and Vertical radius of corner arcs */
    protected Dimension arcs = new Dimension(10, 10);
    /** Distance between border of shadow and border of opaque panel */
    protected int shadowGap = 2;
    /** The offset of shadow. */
    protected int shadowOffset = 4;

    @Override
    protected void paintComponent(Graphics g) {
      super.paintComponent(g);
      int width = getWidth();
      int height = getHeight();
      int shadowGap = this.shadowGap;
      Graphics2D graphics = (Graphics2D) g;

      graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
          RenderingHints.VALUE_ANTIALIAS_ON);

      // 2 colori che fanno la sfumatura

      Point2D.Float p1 = new Point2D.Float(0.f, 75.f); // Gradient line
      // start
      Point2D.Float p2 = new Point2D.Float(0.f, 0.f); // Gradient line end
      GradientPaint g1 = new GradientPaint(p1, new Color(143, 143, 143), p2,
          new Color(220, 243, 243), true);
      graphics.setPaint(g1);
      graphics.fillRoundRect(shadowOffset,// X position
          shadowOffset,// Y position
          width - strokeSize - shadowOffset, // width
          height - strokeSize - shadowOffset, // height
          arcs.width, arcs.height);// arc Dimension

      // Draws the rounded opaque panel with borders.

      graphics.fillRoundRect(0, 0, width - shadowGap, height - shadowGap,
          arcs.width, arcs.height);
      graphics.setColor(getForeground());
      graphics.setStroke(new BasicStroke(strokeSize));

      graphics.drawRoundRect(0, 0, width - shadowGap, height - shadowGap,
          arcs.width, arcs.height);

      // Sets strokes to default, is better.
      graphics.setStroke(new BasicStroke());
      // graphics.drawString(getText(), 20, 20);
    }
  };

  /**
   * APRI PROGETTO
   */
  public JMenu apriProgetto = new JMenu("APRI PROGETTO");
  /**
   * username ftp
   */
  public String username;
  /**
   * password ftp
   */
  public String password;

  // tab
  private BuildingData datiEdificio;
  private Premesse premesse;
  private PuntiRilevazione rilevazione;
  private PuntoCritico critico;
  private Piantina piantina;
  private Sali sali;
  private PotenzialiOrizzontali orizzontali;
  private PotenzialiVerticali verticali;
  private Conclusioni conclusioni;
  private DatiEdificio edificio;
  private Strumenti strumenti;

  public StartingWindow() {

    // ottengo dimensioni schermo
    Rectangle maxBounds = GraphicsEnvironment.getLocalGraphicsEnvironment()
        .getMaximumWindowBounds();
    height = maxBounds.height;
    width = maxBounds.width;
    window.setSize(width, height);
    window
        .setIconImage(new ImageIcon(ClassLoader.getSystemResource("icon.jpg"))
            .getImage());
    window.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
    window.addWindowListener(new WindowsClosing());

    // apri progetto in locale
    apriProgetto.setIcon(new ImageIcon(ClassLoader
        .getSystemResource("apri.png")));
    apriProgetto.setContentAreaFilled(false);
    apriProgetto.setPreferredSize(new Dimension(width / 6, 25));

    // set menubar
    menubar.add(apriProgetto);
    menubar.setPreferredSize(new Dimension(width, 40));
    window.setJMenuBar(menubar);

    avvio();

    projectPanel.setLayout(new MigLayout());
    projectPanel.setPreferredSize(new Dimension(width, height));

    projectPanel.add(tab, "dock north ,gapleft 5, width " + width * 9.4 / 10
        + ":" + width * 9.4 / 10 + ":" + width * 9.4 / 10 + ",height " + height
        * 8 / 10 + ":" + height * 8 / 10 + ":" + height * 8 / 10);
    // tab.setPreferredSize(new Dimension(width, height * 8 / 10));
    window.setContentPane(tab);

    tagList = (new TagPuntiCritici()).getTag();
    addOption();
    nuovo();
    refresh();

    window.setVisible(true);
  }

  /**
   * crea cartella di sistema 'ArchimedeSuper'
   */
  void avvio() {
    // accesso alla cartella di sistema nella home del pc
    Properties pc = System.getProperties();
    String homePath = pc.getProperty("user.home");
    File aa = new File(homePath + pc.getProperty("file.separator")
        + "ArchimedeSuper");
    // se non esiste già la creo
    if (!aa.exists())
      aa.mkdir();
    setProjectListFromPC();
    setRtd();
  }

  /**
   * crea la lista di progetti caricabili nel menu 'Apri progetto'
   */
  public void setProjectListFromPC() {
    // System.out.println(" rimozione elementi dalla lista : " +
    // apriProgetto.getItemCount());
    apriProgetto.removeAll();
    // System.out.println(" nuova lista : " + apriProgetto.getItemCount());
    lastCountRtd = 0;
    Properties pc = System.getProperties();
    String homePath = pc.getProperty("user.home");
    String directoryProject = homePath + pc.getProperty("file.separator")
        + "ArchimedeSuper";

    // System.out.println("directory : " + directoryProject);
    File root = new File(directoryProject);
    File[] allProject = root.listFiles();
    for (int i = 0; i < allProject.length; i++) {
      // System.out.println("enter for");
      if (allProject[i].isDirectory()) {
        if (!allProject[i].getName().contains("_delete")) {
          // System.out.println("** subdirectory : " + allProject[i].getName());
          JMenuItem tp = new JMenuItem(allProject[i].getName());
          // System.out.println("<<"+list[i].getName());
          tp.addActionListener(new LoadProject(allProject[i].getName()));
          apriProgetto.add(tp);
        }
      }

    }
    // System.out.println(" locale : " + apriProgetto.getItemCount());
    // refresh();
  }

  /**
   * aggiorna contatore rtd
   */
  public void setRtd() {
    lastCountRtd = 0;
    Properties pc = System.getProperties();
    String homePath = pc.getProperty("user.home");
    String directoryProject = homePath + pc.getProperty("file.separator")
        + "ArchimedeSuper";

    // System.out.println("directory : " + directoryProject);
    File root = new File(directoryProject);
    File[] allProject = root.listFiles();
    for (int i = 0; i < allProject.length; i++) {
      // System.out.println("enter for");
      if (allProject[i].isDirectory()) {
        lastCountRtd++;
      }
    }
    lastCountRtd++;
    countRtd = lastCountRtd;
  }

  /**
   * crea nuovo progetto
   */
  public void nuovo() {
    // resetto tutti i valori
    tab.removeAll();
    // inizializza nuovi oggetti
    edificio = new DatiEdificio(StartingWindow.this);
    datiEdificio = new BuildingData(StartingWindow.this, edificio);
    premesse = new Premesse(StartingWindow.this);
    rilevazione = new PuntiRilevazione(StartingWindow.this);
    critico = new PuntoCritico(StartingWindow.this, tagList);
    piantina = new Piantina(StartingWindow.this);
    sali = new Sali(StartingWindow.this);
    verticali = new PotenzialiVerticali(StartingWindow.this);
    orizzontali = new PotenzialiOrizzontali(StartingWindow.this);
    conclusioni = new Conclusioni(this);
    strumenti = new Strumenti();

    // aggiungo tab
    tab.add("Dati edificio", new JScrollPane(edificio,
        JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
        JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED) {
      @Override
      public void setVerticalScrollBar(JScrollBar verticalScrollBar) {
        // TODO Auto-generated method stub
        verticalScrollBar.setUnitIncrement(15);
        super.setVerticalScrollBar(verticalScrollBar);
      }
    });
    tab.add("Premesse", new JScrollPane(premesse,
        JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
        JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED) {
      @Override
      public void setVerticalScrollBar(JScrollBar verticalScrollBar) {
        // TODO Auto-generated method stub
        verticalScrollBar.setUnitIncrement(15);
        super.setVerticalScrollBar(verticalScrollBar);
      }
    });
    tab.add("Immobile", new JScrollPane(datiEdificio,
        JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
        JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED) {
      @Override
      public void setVerticalScrollBar(JScrollBar verticalScrollBar) {
        // TODO Auto-generated method stub
        verticalScrollBar.setUnitIncrement(15);
        super.setVerticalScrollBar(verticalScrollBar);
      }
    });
    tab.add("Strumenti", new JScrollPane(strumenti,
        JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
        JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED) {
      @Override
      public void setVerticalScrollBar(JScrollBar verticalScrollBar) {
        // TODO Auto-generated method stub
        verticalScrollBar.setUnitIncrement(15);
        super.setVerticalScrollBar(verticalScrollBar);
      }
    });
    tab.add("Punti misurazione", rilevazione);
    tab.add("Punti critici", critico);
    tab.add("Pianta con punti", new JScrollPane(piantina,
        JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
        JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED) {
      @Override
      public void setVerticalScrollBar(JScrollBar verticalScrollBar) {
        // TODO Auto-generated method stub
        verticalScrollBar.setUnitIncrement(15);
        super.setVerticalScrollBar(verticalScrollBar);
      }
    });
    tab.add("Sali", new JScrollPane(sali,
        JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
        JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED) {
      @Override
      public void setVerticalScrollBar(JScrollBar verticalScrollBar) {
        // TODO Auto-generated method stub
        verticalScrollBar.setUnitIncrement(15);
        super.setVerticalScrollBar(verticalScrollBar);
      }
    });
    tab.add("Tensione verticale", new JScrollPane(verticali,
        JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
        JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED) {
      @Override
      public void setVerticalScrollBar(JScrollBar verticalScrollBar) {
        // TODO Auto-generated method stub
        verticalScrollBar.setUnitIncrement(15);
        super.setVerticalScrollBar(verticalScrollBar);
      }
    });

    tab.add("Tensione orizzontale", new JScrollPane(orizzontali,
        JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
        JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED) {
      @Override
      public void setVerticalScrollBar(JScrollBar verticalScrollBar) {
        // TODO Auto-generated method stub
        verticalScrollBar.setUnitIncrement(15);
        super.setVerticalScrollBar(verticalScrollBar);
      }
    });
    tab.add("Conclusioni", new JScrollPane(conclusioni,
        JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
        JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED) {
      @Override
      public void setVerticalScrollBar(JScrollBar verticalScrollBar) {
        // TODO Auto-generated method stub
        verticalScrollBar.setUnitIncrement(15);
        super.setVerticalScrollBar(verticalScrollBar);
      }
    });

    setRtd();
    countRtd = lastCountRtd;
    window.setTitle("EUREKA - ARCHIMEDE" + " ~ Progetto " + countRtd);
  }

  /**
   * metodo ausiliario per ridisegnare la finestra
   */
  public void refresh() {
    window.paintAll(window.getGraphics());
  }

  /**
   * aggiunge azioni ai pulsanti
   */
  public void addOption() {

    // salva in locale i dati, non li invia al server
    JButton salva = new JButton("SALVA", new ImageIcon(
        ClassLoader.getSystemResource("salva.png")));
    salva.setContentAreaFilled(false);
    salva.setRolloverEnabled(true);
    salva
        .setToolTipText("Salva il progetto, attendere il messaggio di conferma");
    salva.setRolloverIcon(new ImageIcon(ClassLoader
        .getSystemResource("salva_roll.png")));
    // invia al server il progetto
    JButton invia = new JButton("INVIA", new ImageIcon(
        ClassLoader.getSystemResource("invia-file.png")));
    invia.setContentAreaFilled(false);
    invia.setRolloverEnabled(true);
    invia
        .setToolTipText("Invia il progetto, attendere il messaggio di conferma");
    invia.setRolloverIcon(new ImageIcon(ClassLoader
        .getSystemResource("invia-file_roll.png")));
    // cancella progetto in locale (crea direcotory vuota per mantenere rtd
    JButton elimina = new JButton("ELIMINA", new ImageIcon(
        ClassLoader.getSystemResource("elimina-file.png")));
    elimina.setContentAreaFilled(false);
    elimina.setRolloverEnabled(true);
    elimina.setToolTipText("Elimina il progetto");
    elimina.setRolloverIcon(new ImageIcon(ClassLoader
        .getSystemResource("elimina-file_roll.png")));

    // nuovo progetto
    JButton nuovo = new JButton("NUOVO", new ImageIcon(
        ClassLoader.getSystemResource("nuovo.png")));
    nuovo.setContentAreaFilled(false);
    nuovo.setRolloverEnabled(true);
    nuovo.setToolTipText("Crea un nuovo progetto");
    nuovo.setRolloverIcon(new ImageIcon(ClassLoader
        .getSystemResource("nuovo_roll.png")));

    // scarica dal server
    JButton download = new JButton("Download", new ImageIcon(
        ClassLoader.getSystemResource("apri.png")));
    download.setContentAreaFilled(false);
    download.setRolloverEnabled(true);
    download.setToolTipText("Scarica progetti dal server");
    download.setRolloverIcon(new ImageIcon(ClassLoader
        .getSystemResource("apri_roll.png")));

    // crea pdf salvando in locale i dati, non li invia al server
    JButton pdf = new JButton("PDF", new ImageIcon(
        ClassLoader.getSystemResource("pdf.png")));
    pdf.setContentAreaFilled(false);
    pdf.setRolloverEnabled(true);
    pdf.setRolloverIcon(new ImageIcon(ClassLoader
        .getSystemResource("pdf_roll.png")));

    // dimensioni
    salva.setPreferredSize(new Dimension(width / 7, 25));
    invia.setPreferredSize(new Dimension(width / 7, 25));
    elimina.setPreferredSize(new Dimension(width / 7, 25));
    nuovo.setPreferredSize(new Dimension(width / 7, 25));
    download.setPreferredSize(new Dimension(width / 7, 25));
    pdf.setPreferredSize(new Dimension(width / 7, 25));

    // PDF
    pdf.addActionListener(new ActionListener() {

      @Override
      public void actionPerformed(ActionEvent arg0) {
        // salva in locale
        save();

        // crea pdf
        Document document = new Document(PageSize.A4, 45, 45, 80, 35);
        try {
          // seleziona dove salvare pdf
          JFileChooser fc = new JFileChooser();
          fc.setSelectedFile(new File(nameProject + ".pdf"));
          int returnVal = fc.showSaveDialog(StartingWindow.this.window);
          if (returnVal == JFileChooser.APPROVE_OPTION) {
            File file = fc.getSelectedFile();
            // This is where a real application would save the file.
            if (!file.getAbsolutePath().endsWith(".pdf")) {

              file = new File(file.getAbsolutePath() + ".pdf");
            }
            PdfWriter writer = PdfWriter.getInstance(document,
                new FileOutputStream(file));
            writer.setBoxSize("art", new com.itextpdf.text.Rectangle(26, 44,
                559, 788));

            HeaderFooter event = new HeaderFooter();
            writer.setPageEvent(event);
            // TODO
            document.open();
            datiEdificio.PDFintro(document, writer);
            premesse.PDF(document);
            datiEdificio.PDFdati(document);
            strumenti.pdf(document);
            piantina.pdf(document);
            rilevazione.pdf(document);
            sali.pdf(document);
            verticali.pdf(document, orizzontali);
            critico.pdf(document);
            conclusioni.pdf(document);
            document.close();

          } else {
            // log.append("Save command cancelled by user." +
            // newline);
          }

        } catch (Exception e) {
          JOptionPane.showMessageDialog(null, "PDF non creato");
          e.printStackTrace();
        }
      }
    });

    // invia al server il progetto
    invia.addActionListener(new ActionListener() {

      @Override
      public void actionPerformed(ActionEvent e) {
        // salva in locale
        save();
        Properties pc = System.getProperties();
        String homePath = pc.getProperty("user.home");
        String directoryProject = homePath + pc.getProperty("file.separator")
            + "ArchimedeSuper" + pc.getProperty("file.separator") + nameProject;
        new InviaProgetto(directoryProject);
      }
    });

    // salva in locale
    salva.addActionListener(new ActionListener() {

      @Override
      public void actionPerformed(ActionEvent arg0) {
        // salva in locale
        if (save())
          JOptionPane.showMessageDialog(null, "Progetto salvato");
        setProjectListFromPC();
      }
    });

    // elimina il progetto in locale
    elimina.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent arg0) {
        int ris = JOptionPane.showConfirmDialog(null,
            "Vuoi eliminare questo progetto?");
        // si
        if (ris == 0) {
          int removeAll = JOptionPane.showConfirmDialog(null,
              "Vuoi eliminare il progetto anche dal server?");
          if (removeAll == 0) {
            // elimina anche sal server
            Properties pc = System.getProperties();
            String homePath = pc.getProperty("user.home");
            String directoryProject = homePath
                + pc.getProperty("file.separator") + "ArchimedeSuper"
                + pc.getProperty("file.separator")
                + StartingWindow.this.nameProject;

            // accesso al server
            Delete d = new Delete(StartingWindow.this, nameProject,
                directoryProject);
            Thread t = new Thread(d);
            t.start();
          } else {
            // elimina in locale
            Properties pc = System.getProperties();
            String homePath = pc.getProperty("user.home");
            String directoryProject = homePath
                + pc.getProperty("file.separator") + "ArchimedeSuper"
                + pc.getProperty("file.separator") + nameProject;
            File dirtmp = new File(directoryProject);
            if (dirtmp.exists()) {
              try {
                // System.out.println("to delete ------> " + directoryProject);
                FileUtils.forceDelete(dirtmp);
              } catch (IOException e) {
                // System.out.println("error ------> " + directoryProject);
                e.printStackTrace();
              }
            }
            directoryProject = directoryProject + "_delete";
            dirtmp = new File(directoryProject);
            dirtmp.setWritable(false);
            dirtmp.mkdir();
            nuovo();
            setProjectListFromPC();
          }
        }
      }
    });

    // nuovo
    nuovo.addActionListener(new ActionListener() {

      @Override
      public void actionPerformed(ActionEvent e) {
        if (!StartingWindow.this.nameProject.equals(null))
          save();
        nuovo();
      }
    });

    // scarica lista progetti
    download.addActionListener(new ActionListener() {

      @Override
      public void actionPerformed(ActionEvent e) {
        setProjectListFromPC();
        new Credenziali();
      }
    });

    menubar.add(new JSeparator(SwingConstants.VERTICAL));
    menubar.add(download);
    menubar.add(new JSeparator(SwingConstants.VERTICAL));
    menubar.add(salva);
    menubar.add(new JSeparator(SwingConstants.VERTICAL));
    menubar.add(invia);
    menubar.add(new JSeparator(SwingConstants.VERTICAL));
    menubar.add(elimina);
    menubar.add(new JSeparator(SwingConstants.VERTICAL));
    menubar.add(nuovo);
    menubar.add(new JSeparator(SwingConstants.VERTICAL));
    menubar.add(pdf);
  }

  /**
   * salvare i dati del progetto corrente in locale
   */
  public boolean save() {

    // controllo se cambiato nome del progetto
    if (nameProject != null)
      if (!nameProject.equals(datiEdificio.getProgetto())) {
        // System.out.println("------>  mod name " + datiEdificio.getProgetto()
        // + " --- " + nameProject);
        premesse.replace(datiEdificio.getProgetto(), nameProject);
        rilevazione.replace(datiEdificio.getProgetto(), nameProject);
        critico.replace(datiEdificio.getProgetto(), nameProject);
        sali.replace(datiEdificio.getProgetto(), nameProject);
        orizzontali.replace(datiEdificio.getProgetto(), nameProject);
        verticali.replace(datiEdificio.getProgetto(), nameProject);
        conclusioni.replace(datiEdificio.getProgetto(), nameProject);
      }

    nameProject = datiEdificio.getProgetto();
    if (nameProject != null) {
      Properties pc = System.getProperties();
      String homePath = pc.getProperty("user.home");

      String directoryProject = homePath + pc.getProperty("file.separator")
          + "ArchimedeSuper" + pc.getProperty("file.separator")
          + datiEdificio.getProgetto();
      // System.out.println("------> " + directoryProject);

      // creo directory del progetto
      File directory = new File(directoryProject);
      if (!directory.exists()) {
        directory.mkdir();

        // creo le sotto cartelle di extra
        File sub = new File(directoryProject + pc.getProperty("file.separator")
            + "extra");
        sub.mkdir();

        sub = new File(sub + pc.getProperty("file.separator") + "foto"
            + pc.getProperty("file.separator") + "punti_misurazione");
        sub.mkdirs();
        sub = new File(directoryProject + pc.getProperty("file.separator")
            + "extra" + pc.getProperty("file.separator") + "foto"
            + pc.getProperty("file.separator") + "punti_critici");
        sub.mkdir();
        sub = new File(directoryProject + pc.getProperty("file.separator")
            + "extra" + pc.getProperty("file.separator") + "foto"
            + pc.getProperty("file.separator") + "tensione_orizzontale");
        sub.mkdir();
        sub = new File(directoryProject + pc.getProperty("file.separator")
            + "extra" + pc.getProperty("file.separator") + "foto"
            + pc.getProperty("file.separator") + "tensione_verticale");
        sub.mkdir();
        sub = new File(directoryProject + pc.getProperty("file.separator")
            + "extra" + pc.getProperty("file.separator") + "foto"
            + pc.getProperty("file.separator") + "premesse");
        sub.mkdir();
        sub = new File(directoryProject + pc.getProperty("file.separator")
            + "extra" + pc.getProperty("file.separator") + "foto"
            + pc.getProperty("file.separator") + "sali");
        sub.mkdir();
        sub = new File(directoryProject + pc.getProperty("file.separator")
            + "extra" + pc.getProperty("file.separator") + "foto"
            + pc.getProperty("file.separator") + "pianta");
        sub.mkdir();

        sub = new File(directoryProject + pc.getProperty("file.separator")
            + "extra" + pc.getProperty("file.separator")
            + "cliente_collaboratore");
        sub.mkdir();

        sub = new File(directoryProject + pc.getProperty("file.separator")
            + "extra" + pc.getProperty("file.separator") + "documenti");
        sub.mkdir();

        sub = new File(directoryProject + pc.getProperty("file.separator")
            + "extra" + pc.getProperty("file.separator") + "termografia");
        sub.mkdir();

        sub = new File(directoryProject + pc.getProperty("file.separator")
            + "extra" + pc.getProperty("file.separator") + "termografia"
            + pc.getProperty("file.separator") + "premesse");
        sub.mkdir();

        sub = new File(directoryProject + pc.getProperty("file.separator")
            + "extra" + pc.getProperty("file.separator") + "termografia"
            + pc.getProperty("file.separator") + "punti_misurazione");
        sub.mkdir();

        sub = new File(directoryProject + pc.getProperty("file.separator")
            + "extra" + pc.getProperty("file.separator") + "termografia"
            + pc.getProperty("file.separator") + "punti_critici");
        sub.mkdir();
      }

      // salvo i dati
      File fileSave = new File(directoryProject
          + pc.getProperty("file.separator") + countRtd + ".txt");
      try {
        boolean old = fileSave.renameTo(new File(directoryProject
            + pc.getProperty("file.separator") + "last.txt"));
        fileSave.createNewFile();
        try {
          FileWriter fw = new FileWriter(fileSave);
          BufferedWriter bw = new BufferedWriter(fw);
          PrintWriter outFile = new PrintWriter(bw);

          String print = datiEdificio.print();
          print = print + premesse.print();
          print = print + strumenti.print();
          print = print + rilevazione.print();
          print = print + critico.print();
          print = print + sali.print();
          print = print + conclusioni.print();
          print = print + piantina.print();
          print = print + verticali.print();
          print = print + orizzontali.print();

          outFile.println(print);

          try {
            Thread.sleep(200);
          } catch (InterruptedException e) {
            e.printStackTrace();
          }
          outFile.close();

          // salvo foto
          boolean error = false;
          String errorString = "";
          if (!premesse.save()) {
            error = true;
            errorString = "Errore foto in premesse";
          }
          if (!rilevazione.save()) {
            error = true;
            errorString = errorString + "/nErrore foto in punti di rilevazione";
          }
          if (!critico.save()) {
            error = true;
            errorString = errorString + "/nErrore foto in punti critici";
          }

          if (!sali.save()) {
            error = true;
            errorString = errorString + "/nErrore foto in sali";
          }
          if (!orizzontali.save()) {
            error = true;
            errorString = errorString + "/nErrore foto in orizzontali";
          }
          if (!verticali.save()) {
            error = true;
            errorString = errorString + "/nErrore foto in verticali";
          }
          if (!conclusioni.save()) {
            error = true;
            errorString = errorString + "/nErrore foto in conclusioni";
          }

          piantina.save();

          // se c'è errore segnalo e provo a salvare le altre foto
          if (error) {
            JOptionPane.showMessageDialog(null, errorString);
            refresh();
            try {
              Thread.sleep(500);
            } catch (InterruptedException e) {
              e.printStackTrace();
            }
            save();
          }

        } catch (Exception e) {
          if (old)
            JOptionPane
                .showMessageDialog(
                    null,
                    "Riprova errore nella modifica del file. La versione precedente è stata salvata");
          e.printStackTrace();
          return false;
        }
      } catch (IOException e2) {
        JOptionPane
            .showMessageDialog(
                null,
                "Riprova errore nella crezione del file. La versione precedente è stata salvata");
        e2.printStackTrace();
        return false;
      }

      return true;
    }
    return false;
  }

  /**
   * classe interna per aprire il progetto selezionato a caricare i dati salvati
   * 
   * @author Alex
   */
  public class Open implements ActionListener {
    /**
     * numero progetto
     */
    private int n;
    /**
     * nome del progetto
     */
    private String progetto;
    /**
		 * 
		 */
    private int type;
    /**
		 * 
		 */
    private String author;

    /**
     * @param name
     *          nome progetto
     * @param type
     *          amministratore o silver
     */

    Open(String name, int type, String author) {
      progetto = name;
      this.type = type;
      this.author = author;
      try {
        n = Integer.parseInt(name.substring(0, 3));
      } catch (Exception e) {
        try {
          n = Integer.parseInt(name.substring(0, 2));
        } catch (Exception e2) {
          try {
            n = Integer.parseInt(name.substring(0, 1));
          } catch (Exception e3) {
            n = 0;
          }
        }
      }

      // System.out.println("addActionListener " + n);
    }

    public void actionPerformed(ActionEvent e) {
      nuovo();
      countRtd = n;
      nameProject = progetto;
      // reset dati precedenti

      int risposta = JOptionPane.showConfirmDialog(null,
          "Scaricare anche gli allegati?");
      if (risposta == 0) {
        Download d = new Download(StartingWindow.this, author, nameProject,
            progetto, countRtd, password, username, risposta, type);
        Thread thread = new Thread(d);
        thread.start();

      } else if (risposta == 1) {
        // caricamento file
        Download d = new Download(StartingWindow.this, author, nameProject,
            progetto, countRtd, password, username, risposta, type);
        Thread thread = new Thread(d);
        thread.start();
      }

    }

  }

  // carica il progetto
  public void setField(int index, String content) {
    if (index == 0)
      datiEdificio.setFields(content);
    else if (index == 1)
      premesse.setElement(content);
    else if (index == 2)
      strumenti.setElement(content);
    else if (index == 3)
      rilevazione.setElement(content);
    else if (index == 4)
      critico.setElement(content);
    else if (index == 5)
      sali.setElement(content);
    else if (index == 6)
      conclusioni.setElement(content);
    else if (index == 7)
      conclusioni.setProfessionista(content);

    else if (index == 8)
      piantina.setElement(content);
    else if (index == 9)
      verticali.setElement(content);
    else if (index == 10)
      orizzontali.setElement(content);
  }

  private class LoadProject implements ActionListener {
    /**
     * numero progetto
     */
    private int n;
    /**
     * nome del progetto
     */
    private String progetto;

    LoadProject(String name) {
      progetto = name;
      try {
        n = Integer.parseInt(name.substring(0, 3));
      } catch (Exception e) {
        try {
          n = Integer.parseInt(name.substring(0, 2));
        } catch (Exception e2) {
          try {
            n = Integer.parseInt(name.substring(0, 1));
          } catch (Exception e3) {
            n = 0;
          }
        }
      }

      // System.out.println("addActionListener " + n);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
      nuovo();
      countRtd = n;
      nameProject = progetto;
      Properties pc = System.getProperties();
      String homePath = pc.getProperty("user.home");
      String directoryProject = homePath + pc.getProperty("file.separator")
          + "ArchimedeSuper" + pc.getProperty("file.separator") + progetto;

      // file di salvataggio
      String filePath = directoryProject + pc.getProperty("file.separator")
          + countRtd + ".txt";

      File toScan = new File(filePath);

      try {
        Scanner c = new Scanner(toScan);
        int index = 0;
        String done = "";
        while (c.hasNextLine()) {
          String tmp = c.nextLine();
          if (tmp.contains("@@")) {
            setField(index, done);
            done = "";
            index++;

          } else
            done = done + "\n" + tmp;
        }
        c.close();

      } catch (FileNotFoundException e1) {

        e1.printStackTrace();
      }
      window.setTitle("EUREKA - ARCHIMEDE" + " ~ Progetto " + countRtd);
    }

    public void setField(int index, String content) {
      if (index == 0)
        datiEdificio.setFields(content);
      else if (index == 1)
        premesse.setElement(content);
      else if (index == 2)
        strumenti.setElement(content);
      else if (index == 3)
        rilevazione.setElement(content);
      else if (index == 4)
        critico.setElement(content);
      else if (index == 5)
        sali.setElement(content);
      else if (index == 6)
        conclusioni.setElement(content);
      else if (index == 7)
        conclusioni.setProfessionista(content);

      else if (index == 8)
        piantina.setElement(content);
      else if (index == 9)
        verticali.setElement(content);
      else if (index == 10)
        orizzontali.setElement(content);
    }

  }

  /**
   * classe interna per creare intestazione e fronte e pie di pagina
   * 
   * @author tomaseo
   */
  class HeaderFooter extends PdfPageEventHelper {
    /** The header text. */
    String header;
    /** The template with the total number of pages. */
    PdfTemplate total;

    /**
     * Allows us to change the content of the header.
     * 
     * @param header
     *          The new header String
     */
    public void setHeader(String header) {
      this.header = header;
    }

    /**
     * Creates the PdfTemplate that will hold the total number of pages.
     * 
     * @see com.itextpdf.text.pdf.PdfPageEventHelper#onOpenDocument(com.itextpdf.text.pdf.PdfWriter,
     *      com.itextpdf.text.Document)
     */
    public void onOpenDocument(PdfWriter writer, Document document) {
      total = writer.getDirectContent().createTemplate(30, 16);
    }

    /**
     * Adds a header to every page
     * 
     * @see com.itextpdf.text.pdf.PdfPageEventHelper#onEndPage(com.itextpdf.text.pdf.PdfWriter,
     *      com.itextpdf.text.Document)
     */
    public void onEndPage(PdfWriter writer, Document document) {

      if (writer.getPageNumber() == 1 || writer.getPageNumber() == 2
          || writer.getPageNumber() == 4 || writer.getPageNumber() == 6) {

      } else if (writer.getPageNumber() != 3) {
        PdfPTable table = new PdfPTable(1);
        try {
          table.setWidths(new int[] { 24 });
          table.setTotalWidth(527);
          table.setLockedWidth(true);
          com.itextpdf.text.Image img = com.itextpdf.text.Image
              .getInstance(ClassLoader.getSystemResource("logo_eureka.jpg"));
          img.setCompressionLevel(9);
          img.scaleToFit(184, 65);

          PdfPCell cell = new PdfPCell(img);
          cell.setHorizontalAlignment(PdfPCell.ALIGN_RIGHT);
          cell.setBorder(PdfPCell.NO_BORDER);
          table.addCell(cell);
          table.writeSelectedRows(0, -1, -303, 827, writer.getDirectContent());
        } catch (DocumentException de) {
          throw new ExceptionConverter(de);
        } catch (MalformedURLException e) {
          e.printStackTrace();
        } catch (IOException e) {
          e.printStackTrace();
        }
        com.itextpdf.text.Rectangle rect = writer.getBoxSize("art");
        ColumnText
            .showTextAligned(
                writer.getDirectContent(),
                Element.ALIGN_CENTER,
                new Phrase(
                    "Archimede Group Sas        via F.Tasca,117        35010 S.Pietro in Gu (PD)        P.I. & Cod. Fisc.:04613330283        R.E.A.:PD404321\nTel 049-7423009                         www.ArchimedeSupergroup.eu                 info@ArchimedeSupergroup.eu",
                    FontFactory.getFont(FontFactory.TIMES, 8, new BaseColor(0,
                        123, 193))), (rect.getLeft() + rect.getRight()) / 2,
                rect.getBottom() - 12, 0);
        ColumnText
            .showTextAligned(
                writer.getDirectContent(),
                Element.ALIGN_CENTER,
                new Phrase(
                    "Tel 049-7423009                            www.archimedegroup.eu                    info@archimedegroup.eu",
                    FontFactory.getFont(FontFactory.TIMES, 8, new BaseColor(0,
                        123, 193))), (rect.getLeft() + rect.getRight()) / 2,
                rect.getBottom() - 23, 0);
        if (writer.getPageNumber() % 2 == 0)
          ColumnText.showTextAligned(
              writer.getDirectContent(),
              Element.ALIGN_CENTER,
              new Phrase("pag. " + writer.getPageNumber(), FontFactory.getFont(
                  FontFactory.TIMES, 8, BaseColor.BLACK)), rect.getLeft(), rect
                  .getBottom() - 23, 0);
        else
          ColumnText.showTextAligned(
              writer.getDirectContent(),
              Element.ALIGN_CENTER,
              new Phrase("pag. " + writer.getPageNumber(), FontFactory.getFont(
                  FontFactory.TIMES, 8, BaseColor.BLACK)), rect.getRight(),
              rect.getBottom() - 23, 0);
      } else {

        com.itextpdf.text.Rectangle rect = writer.getBoxSize("art");
        ColumnText
            .showTextAligned(
                writer.getDirectContent(),
                Element.ALIGN_CENTER,
                new Phrase(
                    "Della presente relazione tecnica ne e' vietata la riproduzione, anche parziale, senza l'autorizzazione di ArchimedeSuper Group",
                    FontFactory.getFont(FontFactory.TIMES, 8, new BaseColor(0,
                        123, 193))), (rect.getLeft() + rect.getRight()) / 2,
                rect.getBottom() - 12, 0);
      }
    }

    /**
     * Fills out the total number of pages before the document is closed.
     * 
     * @see com.itextpdf.text.pdf.PdfPageEventHelper#onCloseDocument(com.itextpdf.text.pdf.PdfWriter,
     *      com.itextpdf.text.Document)
     */
    public void onCloseDocument(PdfWriter writer, Document document) {
      ColumnText.showTextAligned(total, Element.ALIGN_LEFT,
          new Phrase(String.valueOf(writer.getPageNumber() - 1)), 2, 2, 0);
    }
  }

  private class Credenziali extends JFrame {
    /**
     * server
     */
    private FTPClient client = new FTPClient();

    /**
     * insert user
     */
    private JTextField user = new JTextField() {
      protected void paintComponent(Graphics g) {
        if (!isOpaque()) {
          int w = getWidth();
          int h = getHeight();
          Graphics2D g2 = (Graphics2D) g.create();
          g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
              RenderingHints.VALUE_ANTIALIAS_ON);
          g2.setColor(UIManager.getColor("TextField.background"));
          g2.fillRoundRect(0, 0, w - 2, h - 2, 10, 10);
          g2.setColor(Color.BLACK);
          g2.drawRoundRect(0, 0, w - 2, h - 2, 10, 10);
          g2.dispose();
        }
        super.paintComponent(g);
      }
    };

    /**
     * insert pwd
     */
    private JPasswordField pwd = new JPasswordField() {
      protected void paintComponent(Graphics g) {
        if (!isOpaque()) {
          int w = getWidth();
          int h = getHeight();
          Graphics2D g2 = (Graphics2D) g.create();
          g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
              RenderingHints.VALUE_ANTIALIAS_ON);
          g2.setColor(UIManager.getColor("TextField.background"));
          g2.fillRoundRect(0, 0, w - 2, h - 2, 10, 10);
          g2.setColor(Color.BLACK);
          g2.drawRoundRect(0, 0, w - 2, h - 2, 10, 10);
          g2.dispose();
        }
        super.paintComponent(g);
      }
    };
    private JButton ok = new JButton("   entra   ");

    public Credenziali() {
      try {
        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
      } catch (UnsupportedLookAndFeelException localUnsupportedLookAndFeelException) {
      } catch (ClassNotFoundException localClassNotFoundException) {
      } catch (InstantiationException localInstantiationException) {
      } catch (IllegalAccessException localIllegalAccessException) {
      }
      setLayout(new MigLayout());

      pwd.addKeyListener(new KeyListener() {

        @Override
        public void keyTyped(KeyEvent arg0) {

        }

        @Override
        public void keyReleased(KeyEvent arg0) {

        }

        @Override
        public void keyPressed(KeyEvent arg0) {
          if (arg0.getKeyCode() == KeyEvent.VK_ENTER) {
            // try {
            password = new String(pwd.getPassword());
            username = user.getText();

            int risposta = JOptionPane.showConfirmDialog(null,
                "Scaricare i progetti silver?");
            if (risposta == 0) {
              // si
              try {
                // connessione
                client.setPassive(true);
                client.connect("eureka.archimedegroup.eu");
                // login
                client.login(username, password);
                // System.out.println("is p "+client.isPassive());
                //
                client.changeDirectory("ProgettoArchimede");
                client.changeDirectory("AMMINISTRATORE");

                // lista cartelle presenti in AMMINISTRATORE
                FTPFile[] list = client.list();
                for (int i = 0; i < list.length; i++) {
                  // cerco solo le cartelle e le aggiungo al menu
                  try {
                    JMenuItem tp = new JMenuItem(list[i].getName());
                    // System.out.println("<<" + list[i].getName());
                    tp.addActionListener(new Open(list[i].getName(),
                        AMMINISTRATORE, null));
                    tp.setForeground(Color.RED);
                    apriProgetto.add(tp);
                  } catch (Exception e) {
                    // non contiene più il progetto
                  }
                }
                // lista cartelle presenti in SILVER
                client.changeDirectoryUp();
                client.changeDirectory("SILVER");
                FTPFile[] listUser = client.list();
                for (int k = 0; k < listUser.length; k++) {
                  client.changeDirectory(listUser[k].getName());
                  list = client.list();
                  for (int i = 0; i < list.length; i++) {
                    // cerco solo le cartelle e le aggiungo al menu
                    try {
                      JMenuItem tp = new JMenuItem(list[i].getName());
                      // System.out.println("<<" + list[i].getName());
                      tp.addActionListener(new Open(list[i].getName(), SILVER,
                          listUser[k].getName()));
                      tp.setForeground(Color.BLUE);
                      apriProgetto.add(tp);
                    } catch (Exception e) {
                      // non contiene più il progetto
                    }
                  }
                  client.changeDirectoryUp();
                }
                // libero il server
                client.disconnect(true);

                Credenziali.this.setVisible(false);

              } catch (Exception e1) {
                JOptionPane
                    .showMessageDialog(null,
                        "Errore nella connessione. Se il problema persiste riprovare più tardi");
                e1.printStackTrace();
              }
            } else if (risposta == 1) {
              // no
              try {
                // connessione
                client.setPassive(true);
                client.connect("eureka.archimedegroup.eu");
                // login
                client.login(username, password);
                // System.out.println("is p "+client.isPassive());
                //
                client.changeDirectory("ProgettoArchimede");
                client.changeDirectory("AMMINISTRATORE");

                // lista cartelle presenti in AMMINISTRATORE
                FTPFile[] list = client.list();
                for (int i = 0; i < list.length; i++) {
                  // cerco solo le cartelle e le aggiungo al menu
                  try {
                    JMenuItem tp = new JMenuItem(list[i].getName());
                    // System.out.println("<<" + list[i].getName());
                    tp.addActionListener(new Open(list[i].getName(),
                        AMMINISTRATORE, null));
                    tp.setForeground(Color.RED);
                    apriProgetto.add(tp);
                  } catch (Exception e) {
                    // non contiene più il progetto
                  }
                }
                // libero il server
                client.disconnect(true);

                Credenziali.this.setVisible(false);

              } catch (Exception e1) {
                JOptionPane
                    .showMessageDialog(null,
                        "Errore nella connessione. Se il problema persiste riprovare più tardi");
                e1.printStackTrace();
              }
            }

          }

        }
      });

      ok.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
          password = new String(pwd.getPassword());
          username = user.getText();

          int risposta = JOptionPane.showConfirmDialog(null,
              "Scaricare i progetti silver?");
          if (risposta == 0) {
            // si
            try {
              // connessione
              client.setPassive(true);
              client.connect("eureka.archimedegroup.eu");
              // login
              client.login(username, password);
              // System.out.println("is p "+client.isPassive());
              //
              client.changeDirectory("ProgettoArchimede");
              client.changeDirectory("AMMINISTRATORE");

              // lista cartelle presenti in AMMINISTRATORE
              FTPFile[] list = client.list();
              for (int i = 0; i < list.length; i++) {
                // cerco solo le cartelle e le aggiungo al menu
                try {
                  JMenuItem tp = new JMenuItem(list[i].getName());
                  // System.out.println("<<" + list[i].getName());
                  tp.addActionListener(new Open(list[i].getName(),
                      AMMINISTRATORE, null));
                  tp.setForeground(Color.RED);
                  apriProgetto.add(tp);
                } catch (Exception e) {
                  // non contiene più il progetto
                }
              }
              // lista cartelle presenti in SILVER
              client.changeDirectoryUp();
              client.changeDirectory("SILVER");
              FTPFile[] listUser = client.list();
              for (int k = 0; k < listUser.length; k++) {
                client.changeDirectory(listUser[k].getName());
                list = client.list();
                for (int i = 0; i < list.length; i++) {
                  // cerco solo le cartelle e le aggiungo al menu
                  try {
                    JMenuItem tp = new JMenuItem(list[i].getName());
                    // System.out.println("<<" + list[i].getName());
                    tp.addActionListener(new Open(list[i].getName(), SILVER,
                        listUser[k].getName()));
                    tp.setForeground(Color.BLUE);
                    apriProgetto.add(tp);
                  } catch (Exception e) {
                    // non contiene più il progetto
                  }
                }
                client.changeDirectoryUp();
              }
              // libero il server
              client.disconnect(true);

              Credenziali.this.setVisible(false);

            } catch (Exception e1) {
              JOptionPane
                  .showMessageDialog(null,
                      "Errore nella connessione. Se il problema persiste riprovare più tardi");
              e1.printStackTrace();
            }
          } else if (risposta == 1) {
            // no
            try {
              // connessione
              client.setPassive(true);
              client.connect("eureka.archimedegroup.eu");
              // login
              client.login(username, password);
              // System.out.println("is p "+client.isPassive());
              //
              client.changeDirectory("ProgettoArchimede");
              client.changeDirectory("AMMINISTRATORE");

              // lista cartelle presenti in AMMINISTRATORE
              FTPFile[] list = client.list();
              for (int i = 0; i < list.length; i++) {
                // cerco solo le cartelle e le aggiungo al menu
                try {
                  JMenuItem tp = new JMenuItem(list[i].getName());
                  // System.out.println("<<" + list[i].getName());
                  tp.addActionListener(new Open(list[i].getName(),
                      AMMINISTRATORE, null));
                  tp.setForeground(Color.RED);
                  apriProgetto.add(tp);
                } catch (Exception e) {
                  // non contiene più il progetto
                }
              }
              // libero il server
              client.disconnect(true);

              Credenziali.this.setVisible(false);

            } catch (Exception e1) {
              JOptionPane
                  .showMessageDialog(null,
                      "Errore nella connessione. Se il problema persiste riprovare più tardi");
              e1.printStackTrace();
            }
          }
        }
      });
      user.setOpaque(false);
      user.setBorder(BorderFactory.createEmptyBorder(4, 8, 4, 8));
      user.setPreferredSize(new Dimension(100, 30));
      pwd.setOpaque(false);
      pwd.setBorder(BorderFactory.createEmptyBorder(4, 8, 4, 8));
      pwd.setPreferredSize(new Dimension(100, 30));
      add(new JLabel("User"));
      add(user);
      add(new JLabel("Password"));
      add(pwd);
      add(ok, "wrap");
      add(new JLabel(
          "L'operazione di connessione al server può durare diversi secondi"),
          "dock south");
      add(new JLabel("Una volta selezionato il progetto attendere il download"),
          "dock south");

      setVisible(true);
      pack();
      setLocation(StartingWindow.this.getWidth() / 2 - getWidth() / 2,
          StartingWindow.this.getHeight() / 2 - getHeight() / 2);
    }
  }

  /**
   * @param path
   *          :percorso assoluto dell'ultimo file caricato
   */
  public void setPath(String path) {
    lastPath = path;
  }

  /**
   * @return percorso assoluto dell'ultimo file caricato
   */
  public String getPath() {
    return lastPath;
  }

  /**
   * @return larghezza schermo
   */
  public int getWidth() {
    return width;
  }

  /**
   * @return altezza schermo
   */
  public int getHeight() {
    return height;
  }

  /**
   * @return valore rtd corrente
   */
  public int getCount() {
    return countRtd;
  }

  public JFrame getWIndow() {
    return window;
  }

  /**
   * @return valore rtd corrente
   */
  public String getProject() {
    return nameProject;
  }

  private class InviaProgetto extends JFrame {

    /**
     * insert user
     */
    private JTextField user = new JTextField() {
      protected void paintComponent(Graphics g) {
        if (!isOpaque()) {
          int w = getWidth();
          int h = getHeight();
          Graphics2D g2 = (Graphics2D) g.create();
          g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
              RenderingHints.VALUE_ANTIALIAS_ON);
          g2.setColor(UIManager.getColor("TextField.background"));
          g2.fillRoundRect(0, 0, w - 2, h - 2, 10, 10);
          g2.setColor(Color.BLACK);
          g2.drawRoundRect(0, 0, w - 2, h - 2, 10, 10);
          g2.dispose();
        }
        super.paintComponent(g);
      }
    };

    /**
     * insert pwd
     */
    private JPasswordField pwd = new JPasswordField() {
      protected void paintComponent(Graphics g) {
        if (!isOpaque()) {
          int w = getWidth();
          int h = getHeight();
          Graphics2D g2 = (Graphics2D) g.create();
          g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
              RenderingHints.VALUE_ANTIALIAS_ON);
          g2.setColor(UIManager.getColor("TextField.background"));
          g2.fillRoundRect(0, 0, w - 2, h - 2, 10, 10);
          g2.setColor(Color.BLACK);
          g2.drawRoundRect(0, 0, w - 2, h - 2, 10, 10);
          g2.dispose();
        }
        super.paintComponent(g);
      }
    };
    private JButton ok = new JButton("   entra   ");

    public InviaProgetto(final String path) {
      try {
        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
      } catch (UnsupportedLookAndFeelException localUnsupportedLookAndFeelException) {
      } catch (ClassNotFoundException localClassNotFoundException) {
      } catch (InstantiationException localInstantiationException) {
      } catch (IllegalAccessException localIllegalAccessException) {
      }
      setLayout(new MigLayout());

      pwd.addKeyListener(new KeyListener() {

        @Override
        public void keyTyped(KeyEvent arg0) {

        }

        @Override
        public void keyReleased(KeyEvent arg0) {

        }

        @Override
        public void keyPressed(KeyEvent arg0) {
          if (arg0.getKeyCode() == KeyEvent.VK_ENTER) {
            // try {
            password = new String(pwd.getPassword());
            username = user.getText();

            // connessione
            Upload u = new Upload(nameProject, password, username, path,
                StartingWindow.this);
            Thread t = new Thread(u);
            t.start();
            pwd.setText("");
            user.setText("");
            setVisible(false);
          }

        }
      });

      ok.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
          password = new String(pwd.getPassword());
          username = user.getText();

          // connessione
          Upload u = new Upload(nameProject, password, username, path,
              StartingWindow.this);
          Thread t = new Thread(u);
          t.start();
          pwd.setText("");
          user.setText("");
          setVisible(false);
        }

      });
      user.setOpaque(false);
      user.setBorder(BorderFactory.createEmptyBorder(4, 8, 4, 8));
      user.setPreferredSize(new Dimension(100, 30));
      pwd.setOpaque(false);
      pwd.setBorder(BorderFactory.createEmptyBorder(4, 8, 4, 8));
      pwd.setPreferredSize(new Dimension(100, 30));
      add(new JLabel("User"));
      add(user);
      add(new JLabel("Password"));
      add(pwd);
      add(ok, "wrap");
      add(new JLabel(
          "L'operazione di connessione al server può durare diversi secondi"),
          "dock south");

      setVisible(true);
      pack();
      setLocation(StartingWindow.this.getWidth() / 2 - getWidth() / 2,
          StartingWindow.this.getHeight() / 2 - getHeight() / 2);
    }

  }

  private class WindowsClosing implements WindowListener {

    @Override
    public void windowOpened(WindowEvent e) {
    }

    @Override
    public void windowClosing(WindowEvent e) {
      int risposta = JOptionPane
          .showConfirmDialog(null, "Salvare il progetto?");
      if (risposta == 0) {
        if (save())
          System.exit(0);
      } else if (risposta == 1) {
        System.exit(0);
      }

    }

    @Override
    public void windowClosed(WindowEvent e) {
    }

    @Override
    public void windowIconified(WindowEvent e) {
    }

    @Override
    public void windowDeiconified(WindowEvent e) {
    }

    @Override
    public void windowActivated(WindowEvent e) {
    }

    @Override
    public void windowDeactivated(WindowEvent e) {
    }

  }

  /**
   * main
   * 
   * @param args
   */
  public static void main(String[] args) {
    try {
      UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    } catch (UnsupportedLookAndFeelException e) {
    } catch (ClassNotFoundException e) {
    } catch (InstantiationException e) {
    } catch (IllegalAccessException e) {
    }
    new StartingWindow();
  }

}